//
//  PPOtherUserCenterTableViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 8/5/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPOtherUserCenterTableViewController.h"
#import "PPOtherInfoTableViewController.h"
#import "PPPetDetailTableViewController.h"
#import "PPTopicDetailViewController.h"

#import "ChatViewController.h"


#import "PPTopicTableViewCell.h"
#import "PPPetImageCell.h"
#import "PPTopic.h"
#import "PPPetInfo.h"
#import "PPUserInfo.h"
#import "PPImageShowView.h"
//#import "PPConversationManager.h"

#import "PPCustomBGTableView.h"

#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"


@interface PPOtherUserCenterTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIAlertViewDelegate>
@property (nonatomic, strong) NSMutableArray *topicArray;
@property (nonatomic, strong) NSMutableArray *petArray;


@property (weak, nonatomic) IBOutlet PPCustomBGTableView *tableView;
@property (weak, nonatomic) IBOutlet UICollectionView *petCollectionView;
//static view
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailInfoLabel;
@property (weak, nonatomic) IBOutlet UIImageView *userAvatarImageView;



@property (weak, nonatomic) IBOutlet UIButton *addAttention;


@property (weak, nonatomic) PPSystemConfiguraton *config;
//@property (nonatomic) BOOL followType; //接口返回 0是已关注， 1是未关注
@property (nonatomic) int type;//加关注是 1，取消关注是 0

@property (nonatomic) int requestCount;
@property (strong, nonatomic) UIAlertView *applyAlertView;

@end

@implementation PPOtherUserCenterTableViewController
-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (UIAlertView *)applyAlertView
{
    if (!_applyAlertView) {
        _applyAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"跟他打个招呼吧~" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_applyAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    }
    return _applyAlertView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (self.user.gender == USER_MALE) {
        [self.navigationItem setTitle:@"他的主页"];
    }else{
        [self.navigationItem setTitle:@"她的主页"];
    }
    
    [self checkType];
    [self.addAttention addTarget:self action:@selector(focusOperate) forControlEvents:UIControlEventTouchUpInside];
    
    self.requestCount = 0;
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.petCollectionView.dataSource = self;
    self.petCollectionView.delegate = self;

    [self userInfoGet];
    
}


-(void) userInfoGet
{
    [HUD showUIBlockingIndicatorWithText:@"正在加载"];
    [self petDataInit];
    [self userDataInit];
    [self topicDataInit];
}

-(void) userDataInit
{
    [self.userAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:self.user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    UIColor *borderColor = UIColorFromRGB(0xffffff);
    self.userAvatarImageView.layer.borderColor = borderColor.CGColor;
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goInfo)];
    self.userAvatarImageView.userInteractionEnabled = YES;
    recognizer.numberOfTouchesRequired = 1;
    recognizer.numberOfTapsRequired = 1;
    [self.userAvatarImageView addGestureRecognizer:recognizer];
    
    
    self.userNameLabel.text = self.user.userName;
    self.cityLabel.text = self.user.address;
}

-(void) topicDataInit
{
    self.topicArray = [[NSMutableArray alloc] init];
    NSString *url = [PPAPIList getAPIList].PPQueryTopicMsgByUserId;
    NSDictionary *params = @{@"userId": @(self.user.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation , id responseObject){
        NSLog(@"Topic Json is %@",responseObject);
        self.topicArray = [[NSMutableArray alloc] init];
        if (responseObject) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicList = resultMap[@"topicList"];
            for (NSDictionary *topicDic in topicList) {
                NSError *err = nil;
                PPTopic *topic = [[PPTopic alloc] initWithDictionary:topicDic error:&err];
                if (self.topicArray) {
                    [self.topicArray addObject:topic];
                }
                
            }
        }
        [self.tableView reloadData];
        self.detailInfoLabel.text = [NSString stringWithFormat:@"话题：%d / 粉丝：%d / 关注：%d ",self.topicArray.count,self.config.userInfo.fansNum,self.user.followNum];
        self.requestCount++;
        if (self.requestCount == 2) {
            [HUD hideUIBlockingIndicator];
        }
    } failure:^(AFHTTPRequestOperation *operation , NSError *error){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"动态信息获取失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        self.requestCount++;
        if (self.requestCount == 2) {
            [HUD hideUIBlockingIndicator];
        }
    }];
}

-(void)petDataInit
{
    self.petArray = [[NSMutableArray alloc] init];
    NSString *url = [PPAPIList getAPIList].PPQueryPetMsgByUserId;
    NSDictionary *params = @{@"userId":@(self.user.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"Pet Json is %@",responseObject);
        NSDictionary *resultDic = responseObject[@"resultMap"];
        NSArray *petArray = resultDic[@"petList"];
        if (petArray.count > 0) {
            for (NSDictionary *petDic in petArray) {
                NSError *err = nil;
                PPPetInfo *pet = [[PPPetInfo alloc] initWithDictionary:petDic error:&err];
                if (pet) {
                    [self.petArray addObject:pet];
                }
            }
            [self.petCollectionView reloadData];
        }
        self.requestCount++;
        if (self.requestCount == 2) {
            [HUD hideUIBlockingIndicator];
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"宠物信息获取失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        self.requestCount++;
        if (self.requestCount == 2) {
            [HUD hideUIBlockingIndicator];
        }
    }];
}

-(void)goInfo
{
    PPOtherInfoTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherInfoTableViewController"];
    targetVC.user = self.user;
    [self.navigationController pushViewController:targetVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self getCellHeight:indexPath];
}

-(CGFloat) getCellHeight :(NSIndexPath *)indexPath
{
    if (self.topicArray.count > 0) {
        PPTopic *topic = [self.topicArray objectAtIndex:indexPath.row];
        return [PPTopicTableViewCell getCellHeight:topic];
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topicCell"];

    if (self.topicArray.count > 0) {
        PPTopic *topic = [self.topicArray objectAtIndex:indexPath.row];
        if (![topic isEqual:self.topicArray.firstObject]) {
            PPTopic *beforeTopic = [self.topicArray objectAtIndex:indexPath.row - 1];
            [cell cellInitWithTopic:topic andBeforeTopic:beforeTopic];
        }else{
            [cell cellInitWithTopic:topic andBeforeTopic:nil];
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPTopicDetailViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPTopicDetailViewController"];
    targetVC.topic = [self.topicArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:targetVC animated:YES];
}

#pragma mark - Collection
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.petArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetImageCell *cell = [self.petCollectionView dequeueReusableCellWithReuseIdentifier:@"petImageCell" forIndexPath:indexPath];
    PPPetInfo *petInfo = [self.petArray objectAtIndex:indexPath.row];
    [cell.petAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:petInfo.petAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    UIColor *borderColor = UIColorFromRGB(0xffffff);
//    cell.petAvatarImageView.layer.borderColor = borderColor.CGColor;
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetInfo *pet = [self.petArray objectAtIndex:indexPath.row];
    PPPetDetailTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPetDetailTableViewController"];
    targetVC.pet = pet;
    [self.navigationController pushViewController:targetVC animated:YES];
}


#pragma mark - Custom IBAction

- (IBAction)goSingleChat:(id)sender {
    if ([self checkFriend]) {
        //是好友 去聊天
        if (!self.config.isEaseMobLogin) {
            [self hudShowWithString:@"网络问题，暂时无法支持聊天"];
            return;
        }
        //去聊天具体页面
        //如果是好友 直接去聊天页面
        NSString *url = [PPAPIList getAPIList].PPQueryConversationByTargetId;
        NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id)};
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                //查询成功 直接得到会话传入
                NSError *err = nil;
                NSDictionary *resultMap = responseObject[@"resultMap"];
                NSDictionary *conversationDic = resultMap[@"conversation"];
                PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:[NSNumber numberWithInt:conversation.isGroup].boolValue];
                
                [conversation.conversation markMessagesAsRead:YES];
                ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
                
                targetVC.myConversation = conversation;
                targetVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:targetVC animated:YES];
                
                
            }else{
                [PPHUD hudShowWithString:@"会话获取失败" andView:self.view];
                //查询失败
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
        }];
        
    }else{
        //不是好友 先发送好友请求
        [self.applyAlertView textFieldAtIndex:0].text = [NSString stringWithFormat:@"我是%@",self.config.userInfo.userName];
        [self.applyAlertView show];
    }
//    if (self.config.isEaseMobLogin) {
//        if ([self searchIsFriend]) {
//            PPChatViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPChatViewController"];
//            targetVC.user = self.user;
//            [self.navigationController pushViewController:targetVC animated:YES];
//        }else{
//            self.addFriendAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你们还不是好友，是否发送好友请求" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//            [self.addFriendAlert show];
//        }
//    }else{
//        [self alertShow:@"您暂时无法使用该功能"];
//    }
//    
    
}

#pragma mark - Other Method

- (void)hudShowWithString:(NSString *)string
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.labelText = string;
    hud.mode = MBProgressHUDModeText;
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [hud removeFromSuperview];
    }];
}

//关注操作
-(void)focusOperate
{
    NSString *url = [PPAPIList getAPIList].PPFollow;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id),@"type":@(self.type)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber *result = responseObject[@"processResult"];
        if (result.intValue == 1) {
            [self checkType];
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
    }];
}

//检测用户关注关系
-(void)checkType
{
    NSString *url = [PPAPIList getAPIList].PPIsFollow;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(self.user.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"type is %@",responseObject);
        NSDictionary *mapDic = responseObject[@"resultMap"];
        NSNumber *followNum = mapDic[@"followStatus"];
        if (followNum.intValue == 0) {
            //            self.followType = YES;
            //已关注
            self.type = followNum.intValue;
            [self.addAttention setImage:[UIImage imageNamed:@"haveAttention"] forState:UIControlStateNormal];
        }else if (followNum.intValue == 1){
            //            self.followType = NO;
            //未关注
            self.type = followNum.intValue;
            [self.addAttention setImage:[UIImage imageNamed:@"noAttention"] forState:UIControlStateNormal];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"type is %@",error);
    }];
}


//检测用户好关系
- (BOOL)checkFriend
{
    for (PPUserInfo *user in self.config.friendArray) {
        if (user.id == self.user.id) {
            return YES;
        }
    }
    return NO;
}

-(void)alertShow :(NSString *)string
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

#pragma mark - AlertView Delegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView isEqual:self.applyAlertView]) {
        UITextField *messageTextField = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            NSString *url = [PPAPIList getAPIList].PPSendRequest;
            NSDictionary *params = @{@"sendUserId":@(self.config.userInfo.id),@"targetUserId":@(self.user.id),@"message":messageTextField.text};
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber *processResult = responseObject[@"processResult"];
                if (processResult.boolValue) {
                    [self hudShowWithString:@"请求已发送"];
                }else{
                    [self hudShowWithString:@"请求发送失败"];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self hudShowWithString:@"网络错误"];
            }];
        }
    }
}


@end
